package com.code.generator.cn.aop;

import com.alibaba.fastjson.JSON;
import com.code.generator.cn.model.LayPageModel;
import com.code.generator.cn.vo.CommonResposeVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class WebAop {

    /**
     * 设置切入点未restTemplete下的所有方法
     */
    @Pointcut("execution(public * com.code.generator.cn.coder_generator.controller..*.*(..))")
    public void aopController() {

    }



    @Around("aopController()")
    public Object arround(ProceedingJoinPoint pjp) {
        Object[] parames = pjp.getArgs(); //获取目标方法体参数
        //返回公共信息
        return createCommonResponse(pjp, parames);
    }

    private Object createCommonResponse(ProceedingJoinPoint pjp, Object[] parames) {
        //获取request
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        //记录请求路径url
        CommonResposeVo commonResposeVo=null;
        log.info("请求url={},请求方法method={},请求IP地址ip={},传递参数args={}",
                request.getRequestURL(),request.getMethod(),request.getRemoteAddr(),JSON.toJSON(request.getParameterMap()).toString());
        Long startTime=System.currentTimeMillis();
        try {
            Object o = pjp.proceed(parames);

            if(o instanceof ModelAndView || o instanceof LayPageModel){
                return  o;
            }else{
                commonResposeVo =new CommonResposeVo(0,"操作成功",o);
                return commonResposeVo;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.error(e.getMessage());
            commonResposeVo =new CommonResposeVo(-1,"操作失败",null);
            return commonResposeVo;
        }finally {
            Long endTime=System.currentTimeMillis();
            Long reqTimes=endTime-startTime;
            log.info("返回参数："+JSON.toJSONString(commonResposeVo).toString()+"，响应时间毫秒："+reqTimes);
        }

    }

}
